package com.nikolaj.kuzan.gui;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.imageio.ImageIO;

import com.nikolaj.kuzan.controller.Controller;
import com.nikolaj.kuzan.controller.DeleteFrom;
import com.nikolaj.kuzan.controller.OrigSymbols;
import com.nikolaj.kuzan.dao.CsvFileDao;
import com.nikolaj.kuzan.dao.FileDAO;

import com.nikolaj.kuzan.test.WriteExcel;
import com.nikolaj.kuzan.utils.DoubleConverter;
import jxl.write.WriteException;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.neuroph.core.data.DataSet;
import org.neuroph.core.learning.LearningRule;
import org.neuroph.nnet.Hopfield;
import org.neuroph.nnet.learning.BinaryHebbianLearning;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.*;
import java.util.List;

public class MainWindow extends JFrame {

	private static final long serialVersionUID = 1698185868225160515L;
	private static Controller controller;
    private static MainWindow frame;
    private final int IMAGE_SIZE = 50;

    private int countOfImages;
    private Image image;
    private File imageFile;

    private List<File> trainingFiles;
    private List<File> testFiles;

    private JPanel imagePanel;
    private JPanel leftPanel;
    private JPanel rightPanel;
    private JPanel chart_panel;
    private JFreeChart chart;
    private JTable resultTable;
	private JCheckBox chckbxCropp;


    private Double[] inputVector;
    private List<Double[]> inputVectors;
    private DataSet treaningSet;
    private Hopfield origNetwork;
    private Hopfield reducedNetwork;


    private Double[] inputVectorForNoise;

    private boolean isOpenFolderForTest;


	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {

					UIManager.setLookAndFeel(UIManager
							.getSystemLookAndFeelClassName());

					frame = new MainWindow();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
				controller = new Controller();
			}
		});
	}

	public MainWindow() {
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setBounds(100, 100, 700, 420);

        //============================================================================================================//
        //============================================TOP-MAIN-MENU===================================================//
        //============================================================================================================//

        //Top main menu
		JMenuBar topMenuBar = new JMenuBar();
		setJMenuBar(topMenuBar);
    	JMenu fileMenu = new JMenu("File");
		topMenuBar.add(fileMenu);

        //Open file menu item
		JMenuItem openFileMenuItem = new JMenuItem("Open File ...\t");
        openFileMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
        String[] classPathes = System.getProperty("java.class.path").split(";");
        String pathToIcons = "\\..\\resources\\img\\16x16\\open-file-icon.png";
        openFileMenuItem.setIcon(new ImageIcon(classPathes[0] + pathToIcons));
        fileMenu.add(openFileMenuItem);

        //Open folder menu item
        JMenuItem openFolderForTrainMenuItem = new JMenuItem("Open Folder For Train ...");
        countOfImages = 0;
        fileMenu.add(openFolderForTrainMenuItem);

        JMenuItem openFolderForTestMenuItem = new JMenuItem("Open Folder For Test ...");
        fileMenu.add(openFolderForTestMenuItem);


        //Refresh main window menu item
        JMenuItem restartMenuItem = new JMenuItem("Restart");
        fileMenu.add(restartMenuItem);
        pathToIcons = "\\..\\resources\\img\\16x16\\refresh.jpg";
        restartMenuItem.setIcon(new ImageIcon(classPathes[0] + pathToIcons));

        JMenuItem checkForNoiseItem = new JMenuItem("Check for noise");
        fileMenu.add(checkForNoiseItem);

        //============================================================================================================//

        JPanel contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(null);
        setContentPane(contentPane);

        //============================================================================================================//
        //=================================================LEFT PANEL=================================================//
        //============================================================================================================//

        leftPanel = new JPanel();
        leftPanel.setBorder(new LineBorder(Color.LIGHT_GRAY));
        leftPanel.setBounds(3, 3, 120, 350);
        leftPanel.setLayout(null);
        contentPane.add(leftPanel);

        JLabel IMGLabel = new JLabel("IMG");
        IMGLabel.setFont(new Font("Tahoma", Font.BOLD, 22));
        IMGLabel.setBounds(35, 45, 100, 25);

        imagePanel = new JPanel();
        imagePanel.setBorder(new LineBorder(new Color(0, 0, 0)));
        imagePanel.setBackground(Color.WHITE);
        imagePanel.setBounds(1, 2, 118, 118);
        imagePanel.setLayout(null);
        imagePanel.add(IMGLabel);
        leftPanel.add(imagePanel);

        chckbxCropp = new JCheckBox("Cropp image");
		chckbxCropp.setBounds(2, 122, 113, 23);
		leftPanel.add(chckbxCropp);

        final JButton btnAddToDataset = new JButton("To DataSet");
        btnAddToDataset.setBounds(3, 147, 113, 23);
        btnAddToDataset.setEnabled(false);
        leftPanel.add(btnAddToDataset);


        JLabel lblCountOfCycles = new JLabel();
        lblCountOfCycles.setBounds(5, 173, 113, 20);
        lblCountOfCycles.setText("Count of cycles");
        leftPanel.add(lblCountOfCycles);

        final JTextField countOfCycles = new JTextField();
        countOfCycles.setBounds(3, 195, 113, 22);
        leftPanel.add(countOfCycles);



        JButton btnTrain = new JButton("Train");
		btnTrain.setBounds(3, 220, 113, 23);
		leftPanel.add(btnTrain);

        JLabel lblDeleteNeuron = new JLabel();
        lblDeleteNeuron.setBounds(5, 245, 113, 20);
        lblDeleteNeuron.setText("Delete neurons (%)");
        leftPanel.add(lblDeleteNeuron);

        final JTextField percentageOfNeurons = new JTextField();
        percentageOfNeurons.setBounds(3, 270, 113, 20);
        leftPanel.add(percentageOfNeurons);

        JButton btnDeleteNeurons = new JButton("Delete neurons");
        btnDeleteNeurons.setBounds(3, 295, 113, 23);
        leftPanel.add(btnDeleteNeurons);

        JButton btnTest = new JButton("Test");
		btnTest.setBounds(3, 320, 113, 23);
		leftPanel.add(btnTest);

        //============================================================================================================//
        //=============================================RIGHT PANEL====================================================//
        //============================================================================================================//

        rightPanel = new JPanel();
        //rightPanel.setBorder(new LineBorder(Color.LIGHT_GRAY));
        rightPanel.setBounds(125, 3, 555, 350);
        rightPanel.setLayout(null);
        contentPane.add(rightPanel);


        JPanel firstTabPanel = new JPanel();
        JPanel secondTabPanel = new JPanel();
        firstTabPanel.setLayout(null);
        secondTabPanel.setLayout(null);

        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Result Table", firstTabPanel);
        tabbedPane.addTab("Result Chart", secondTabPanel);
        tabbedPane.setBounds(5, 0, 550, 350);
        tabbedPane.setForegroundAt(tabbedPane.getSelectedIndex(), new Color(20, 20, 20));
        rightPanel.add(tabbedPane);



        JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(5, 5, 130, 98);
        firstTabPanel.add(scrollPane);
		
		resultTable = new JTable(null, new String[]{"Number", "Percent"});
		resultTable.setFillsViewportHeight(true);
        resultTable.setBackground(UIManager.getColor("CheckBox.background"));
        resultTable.setSelectionBackground(Color.LIGHT_GRAY);
        resultTable.setBorder(new LineBorder(new Color(0, 0, 0)));
    	resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		resultTable.setToolTipText("");
		resultTable.setModel(new DefaultTableModel(
                new Object[][]{ {null, null}, {null, null}, {null, null}, {null, null}, {null, null}, {null, null} },
                new String[]{ "Number", "Percent" }
        ) {
            Class[] columnTypes = new Class[]{
                    Integer.class, Double.class
            };
            public Class getColumnClass(int columnIndex) {
                return columnTypes[columnIndex];
            }
        });

        scrollPane.setColumnHeaderView(resultTable);

        final JLabel timeLabel = new JLabel();
        timeLabel.setBounds(5, 110, 130, 25);
        timeLabel.setText("Time - ");
        firstTabPanel.add(timeLabel);

        JButton btnSaveTime = new JButton("Save Time");
        btnSaveTime.setBounds(275, 295, 130, 25);
        firstTabPanel.add(btnSaveTime);

        JButton btnShowTimeChart = new JButton("Show Time Chart");
        btnShowTimeChart.setBounds(410, 295, 130, 25);
        firstTabPanel.add(btnShowTimeChart);


        JButton openIMGForMakeNoiseBtn = new JButton("Open IMG");
        openIMGForMakeNoiseBtn.setBounds(5,5,100,25);
        secondTabPanel.add(openIMGForMakeNoiseBtn);


        final JTextField percentOfNoise = new JTextField();
        percentOfNoise.setBounds(5,35,100,25);
        secondTabPanel.add(percentOfNoise);

        JButton addNoiseBtn = new JButton("Add noise");
        addNoiseBtn.setBounds(5,65,100,25);
        secondTabPanel.add(addNoiseBtn);


        //============================================================================================================//
        //============================================================================================================//

        openFileMenuItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent arg0) {
                JFileChooser chooser = new JFileChooser("C:\\Users\\Nikolay\\Desktop");
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "JPG, PNG & GIF Images", "jpg", "gif", "png", "jpeg");

                chooser.setFileFilter(filter);

                int returnValue = chooser.showOpenDialog(MainWindow.frame);

                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    imageFile = chooser.getSelectedFile();
                    testFiles = new ArrayList<>();
                    testFiles.add(imageFile);

                    JPanel imagePanel = new MyDrawPanel();
                    imagePanel.setSize(118, 118);
                    imagePanel.setBounds(6, 7, 108, 108);
                    imagePanel.setBorder(new LineBorder(new Color(0, 0, 0)));
                    try {
                        image = ImageIO.read(imageFile);
                    } catch (IOException e1) {
                        // TODO: Auto-generated catch block
                        e1.printStackTrace();
                    }

                    leftPanel.remove(MainWindow.this.imagePanel);
                    leftPanel.add(imagePanel);

                    try {
                        inputVector = controller.imgFileToInputVector(imageFile, chckbxCropp.isSelected(), IMAGE_SIZE);
                        //controller.addInputVectorToTrainingSet(inputVector);
                        btnAddToDataset.setEnabled(true);
                    } catch (FileNotFoundException e) {
                        JOptionPane.showMessageDialog(null,
                                "Cann't open image file", "Information Window",
                                JOptionPane.ERROR_MESSAGE);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    leftPanel.repaint();
                    leftPanel.revalidate();
                }
            }
        });

        openFolderForTrainMenuItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent arg0) {

                JFileChooser chooser = new JFileChooser("C:\\Users\\Nikolay\\Desktop");
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

                int returnVal = chooser.showOpenDialog(MainWindow.frame);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File directory = chooser.getSelectedFile();

                    File[] allFiles = directory.listFiles();
                    trainingFiles = new ArrayList<>();
                    testFiles = new ArrayList<>();



                    //выбираются только те файлы, которые являются первыми в классе и обозначены ".1."
                    for (File tempFile : allFiles) {
                        System.out.println("Hello");
                        String fileName = tempFile.getName();

                        if (fileName.toLowerCase().contains(".1.".toLowerCase())) {
                            trainingFiles.add(tempFile);
                            testFiles.add(tempFile);
                            resultTable.setValueAt(tempFile.getName(), countOfImages, 0);
                            countOfImages++;
                        }
                    }

                    if (countOfImages == 0){
                        JOptionPane.showMessageDialog(MainWindow.getFrames()[0],
                            "This folder is empty", "Error message",
                            JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    JPanel imagePanel = new MyDrawPanel();
                    imagePanel.setSize(118, 118);
                    imagePanel.setBounds(6, 7, 108, 108);
                    imagePanel.setBorder(new LineBorder(new Color(0, 0, 0)));

                    try {
                        imageFile = trainingFiles.get(0);
                        image = ImageIO.read(trainingFiles.get(0));
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    leftPanel.remove(MainWindow.this.imagePanel);
                    leftPanel.add(imagePanel);

                    try {
                        List<Double[]> inputVectors = controller.imgFilesToInputVectors(trainingFiles, chckbxCropp.isSelected(), IMAGE_SIZE);
                        treaningSet = controller.addInputVectorsToTrainingSet(inputVectors);
                    } catch (FileNotFoundException e) {
                        JOptionPane.showMessageDialog(null,
                                "Cann't open image file", "Error",
                                JOptionPane.ERROR_MESSAGE);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    leftPanel.repaint();
                    leftPanel.revalidate();
                }
            }
        });

        openFolderForTestMenuItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JFileChooser chooser = new JFileChooser("C:\\Users\\Nikolay\\Desktop");
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

                int returnVal = chooser.showOpenDialog(MainWindow.frame);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File directory = chooser.getSelectedFile();

                    File[] allFiles = directory.listFiles();
                    testFiles = new ArrayList<>();

                    for (File tempFile : allFiles) {

                        String fileName = tempFile.getName();

                        if (fileName.toLowerCase().contains(".jpg".toLowerCase()) ||
                                fileName.toLowerCase().contains(".jpeg".toLowerCase()) ||
                                fileName.toLowerCase().contains(".png".toLowerCase()) ||
                                fileName.toLowerCase().contains(".bmp".toLowerCase())) {

                            testFiles.add(tempFile);
                            //resultTable.setValueAt(tempFile.getName(), countOfImages, 0);
                            countOfImages++;
                        }
                    }

                    if (countOfImages == 0){
                        JOptionPane.showMessageDialog(MainWindow.getFrames()[0],
                                "This folder is empty", "Error message",
                                JOptionPane.ERROR_MESSAGE);
                        return;
                    }

                    JPanel imagePanel = new MyDrawPanel();
                    imagePanel.setSize(118, 118);
                    imagePanel.setBounds(6, 7, 108, 108);
                    imagePanel.setBorder(new LineBorder(new Color(0, 0, 0)));

                    try {
                        imageFile = testFiles.get(0);
                        image = ImageIO.read(testFiles.get(0));
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    leftPanel.remove(MainWindow.this.imagePanel);
                    leftPanel.add(imagePanel);
                    leftPanel.repaint();
                    leftPanel.revalidate();

                    isOpenFolderForTest = true;
                }

            }
        });

        restartMenuItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                controller = new Controller();
                frame.setVisible(false);
                frame = new MainWindow();
                frame.setVisible(true);

            }
        });

        checkForNoiseItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JFileChooser chooser = new JFileChooser("C:\\Users\\Nikolay\\Desktop");
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "JPG, PNG & GIF Images", "jpg", "gif", "png", "jpeg");

                chooser.setFileFilter(filter);

                int returnValue = chooser.showOpenDialog(null);

                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    imageFile = chooser.getSelectedFile();
                    JPanel imagePanel = new MyDrawPanel();
                    imagePanel.setSize(118, 118);
                    imagePanel.setBounds(6, 7, 108, 108);
                    imagePanel.setBorder(new LineBorder(new Color(0, 0, 0)));
                    try {
                        image = ImageIO.read(imageFile);
                    } catch (IOException e1) {
                        // TODO: Auto-generated catch block
                        e1.printStackTrace();
                    }

                    leftPanel.remove(MainWindow.this.imagePanel);
                    leftPanel.add(imagePanel);

                    try {
                        Double[] noisedSymbol = controller.imgFileToInputVector(imageFile, chckbxCropp.isSelected(), IMAGE_SIZE);

                        List<Double[]> originalVectors = new ArrayList<>();
                        //originalVectors.add(OrigSymbols.getASymbolVector());
                        ////originalVectors.add(OrigSymbols.getBSymbolVector());
                        ////originalVectors.add(OrigSymbols.getISymbolVector());
                        ////originalVectors.add(OrigSymbols.getKSymbolVector());
                        //originalVectors.add(OrigSymbols.getOSymbolVector());
                        ////originalVectors.add(OrigSymbols.getTSymbolVector());
                        ////originalVectors.add(OrigSymbols.getMSymbolVector());
                        ////originalVectors.add(OrigSymbols.getPSymbolVector());
                        originalVectors.add(OrigSymbols.getCat1Vector());
                        originalVectors.add(OrigSymbols.getCat2Vector());
                        originalVectors.add(OrigSymbols.getPenguinVector());
                        originalVectors.add(OrigSymbols.getFlowersVector());

                        List<Double> similarity = controller.compareVectors(originalVectors, noisedSymbol);

                        for (int i = 0; i < similarity.size(); i++) {
                            resultTable.setValueAt(similarity.get(i), i, 1);
                        }

                    } catch (FileNotFoundException ex) {
                        JOptionPane.showMessageDialog(null,
                                "Cann't open image file", "Information Window",
                                JOptionPane.ERROR_MESSAGE);
                    } catch (IOException ex) {
                        // TODO Auto-generated catch block
                        ex.printStackTrace();
                    }
                    leftPanel.repaint();
                    leftPanel.revalidate();
                }
            }
        });

        btnAddToDataset.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                controller.addInputVectorToTrainingSet(inputVector);
                btnAddToDataset.setEnabled(false);
            }
        });

        btnTrain.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {


                origNetwork = controller.trainNetwork(treaningSet, Integer.parseInt(countOfCycles.getText()));

            }
        });

        btnDeleteNeurons.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                Hopfield tempNetwork = new Hopfield(origNetwork.getInputsCount());
                tempNetwork.setWeights(DoubleConverter.objectDoubleArrToDoubleArr(origNetwork.getWeights()));

                reducedNetwork = controller.deleteNeurons(tempNetwork, Integer.parseInt(percentageOfNeurons.getText()), DeleteFrom.BEGIN);
            }
        });

        btnTest.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {


                List<List<Double>> similarityMatrix = new ArrayList<>();
                for (File imageFile : testFiles){

                    try {
                        Double[] networkOutput = controller.testNetwork(reducedNetwork, imageFile, IMAGE_SIZE, chckbxCropp.isSelected(),
                                                Integer.parseInt(percentageOfNeurons.getText()), DeleteFrom.BEGIN);

                        List<Double> similarity = controller.compareVectors(trainingFiles, networkOutput, Integer.parseInt(percentageOfNeurons.getText()));
                        for (int i = 0; i < similarity.size(); i++) {
                            resultTable.setValueAt(similarity.get(i), i, 1);
                        }

                        similarityMatrix.add(similarity);

                        //controller.imgVectorToImg(networkOutput);

                        timeLabel.setText("Time = " + Integer.toString(controller.getCalcDuration()));

                        Map<Integer, Integer> dataForSave = controller.getTimeOfCalculatingMap();


                        FileDAO dao = new CsvFileDao();
                        dao.saveData(dataForSave, "C:\\Users\\Nikolay\\Desktop\\time.csv");


                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }

                controller.resetTimeOfCalculationMap();

                WriteExcel test = new WriteExcel();

                test.setOutputFile("C:\\Users\\Nikolay\\Desktop\\" + percentageOfNeurons.getText() + "\\" + testFiles.get(0).getParentFile().getName()+".xls");

                try {
                    test.write(similarityMatrix);
                } catch (WriteException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        });

        btnShowTimeChart.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "CSV-File", "csv");
                chooser.setFileFilter(filter);
                int returnValalue = chooser.showOpenDialog(null);


                if (returnValalue == JFileChooser.APPROVE_OPTION) {


                    chart_panel = new JPanel();
                    chart_panel.setBorder(new LineBorder(Color.LIGHT_GRAY));
                    chart_panel.setBounds(0, 0, 415, 300);
                    rightPanel.add(chart_panel);
                    chart_panel.setLayout(null);

                    Map<Double, Double> map;

                    File dataFile = chooser.getSelectedFile();

                    FileDAO dao = new CsvFileDao();
                    try {
                        map = dao.getDataForProcess(dataFile);
                        buildChart(map, map);

                    } catch (IOException e1) {
                        //TODO: replace it
                        e1.printStackTrace();
                    }

                }

            }
        });

        btnSaveTime.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                FileDAO dao = new CsvFileDao();

                JFileChooser fileChooser = new JFileChooser("C:\\Users\\Nikolay\\Desktop");


                if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {

                    File file = fileChooser.getSelectedFile();
                    String path = file.getAbsolutePath();
                    String fileName = file.getName();

                    Map<Integer, Integer> dataForSave = controller.getTimeOfCalculatingMap();
                    dao.saveData(dataForSave, path);
                }
            }
        });

        openIMGForMakeNoiseBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {


                JFileChooser chooser = new JFileChooser("C:\\Users\\Nikolay\\Desktop");
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "JPG, PNG & GIF Images", "jpg", "gif", "png", "jpeg");

                chooser.setFileFilter(filter);

                int returnValue = chooser.showOpenDialog(MainWindow.frame);

                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    imageFile = chooser.getSelectedFile();
                    testFiles = new ArrayList<>();
                    testFiles.add(imageFile);


                    try {
                        inputVectorForNoise = controller.imgFileToInputVector(imageFile, chckbxCropp.isSelected(), IMAGE_SIZE);
                    } catch (FileNotFoundException e2) {
                        JOptionPane.showMessageDialog(null,
                                "Cann't open image file", "Information Window",
                                JOptionPane.ERROR_MESSAGE);
                    } catch (IOException e2) {
                        // TODO Auto-generated catch block
                        e2.printStackTrace();
                    }
                }
            }
        });

        addNoiseBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int percOfNoise = Integer.parseInt(percentOfNoise.getText());
                int countOfElementsForNoise = (int) (((double)inputVectorForNoise.length/100)*percOfNoise);

                Random random = new Random();
                int randomVal;
                List<Integer> listOfRandomValues = new ArrayList<>();

                for(int i = 0; i < countOfElementsForNoise; i++){
                    randomVal = random.nextInt(inputVectorForNoise.length);

                    while (true){
                        if (listOfRandomValues.contains(randomVal)){
                            randomVal = random.nextInt(inputVectorForNoise.length);
                        } else{
                            listOfRandomValues.add(randomVal);
                            break;
                        }
                    }
                }



                for (int i = 0; i < listOfRandomValues.size(); i++){
                    if (inputVectorForNoise[listOfRandomValues.get(i)] == 0.0){
                        inputVectorForNoise[listOfRandomValues.get(i)] = 1.0;
                    } else{
                        inputVectorForNoise[listOfRandomValues.get(i)] = 0.0;
                    }
                }


                controller.imgVectorToImg(inputVectorForNoise, IMAGE_SIZE);


            }
        });
    }

    private void buildChart(Map<Double, Double> dataForChart, Map<Double, Double> origDataForChart){

        chart_panel.removeAll();

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        DefaultCategoryDataset origDataset = new DefaultCategoryDataset();



        Double maxValueInData = (Collections.max(dataForChart.values()));
        Double maxValueInOrigData = (Collections.max(origDataForChart.values()));
        Double minValueInData = (Collections.min(dataForChart.values()));
        Double minValueInOrigData = (Collections.min(origDataForChart.values()));

        double max = 0;
        if(maxValueInData > maxValueInOrigData){
            max = maxValueInData;
        } else{
            max = maxValueInOrigData;
        }

        double min = 0;
        if(minValueInData < minValueInOrigData){
            min = minValueInData;
        } else{
            min = minValueInOrigData;
        }




        for (Map.Entry<Double, Double> entry : dataForChart.entrySet()) {
            double x = entry.getKey();
            double y = entry.getValue();
            dataset.setValue(y, "", entry.getKey());
        }

        for (Map.Entry<Double, Double> entry : origDataForChart.entrySet()) {
            double x = entry.getKey();
            double y = entry.getValue();
            origDataset.setValue(y, "", entry.getKey());
        }

        // create the chart...

        chart = ChartFactory.createBarChart(
                "", // chart title
                "",                // domain axis label
                "",               // range axis label
                origDataset,      // data
                PlotOrientation.VERTICAL,
                false,           // include legend
                false,
                false
        );

        // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

        // set the background color for the chart...
        //chart.setBackgroundPaint(new Color(0xCC, 0xFF, 0xCC));
        //chart.getLegend().setAnchor(Legend.SOUTH);


        final CategoryPlot plot = chart.getCategoryPlot();
        final CategoryItemRenderer renderer1 = plot.getRenderer();
        renderer1.setSeriesPaint(0, new Color(100, 180, 255));

        plot.getRangeAxis().setRange(min, max);




        final ValueAxis axis2 = new NumberAxis("");
        axis2.setRange(min, max);

        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, dataset);
        plot.mapDatasetToRangeAxis(1, 1);


        final CategoryItemRenderer renderer2 = new LineAndShapeRenderer(2);
        renderer2.setSeriesPaint(0, new Color(16, 78, 139));

        plot.setRenderer(1, renderer2);

        plot.setDatasetRenderingOrder(DatasetRenderingOrder.REVERSE);


        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));

        chart_panel.setLayout(new java.awt.BorderLayout());
        chart_panel.add(chartPanel, BorderLayout.CENTER);

        chart_panel.validate();




    }

	public class MyDrawPanel extends JPanel {
		
		private static final long serialVersionUID = 1L;
    	public void paintComponent(Graphics g) {
			g.drawImage(image, 0, 0, this);
		}
	}
}